# coding=utf8

import numpy as np


class Preliminary:

    @staticmethod
    def dtype_conversion():
        """使用dtype初始化方法进行类型转换"""
        # 小整数类型转为大整数类型
        a = np.int8(112)
        print(
            ">>> a = np.int8(112)\n"
            ">>> np.int32(a)\n"
            f"{np.int32(a)}"
        )
        # 大整数类型转为小整数类型
        a = np.int32(1234567)
        print(
            ">>> a = np.int8(1234567)\n"
            ">>> np.int16(1234567)\n"
            f"{np.int16(a)}"
        )
        # 整数转为浮点数
        print(
            ">>> np.float32('123')\n"
            f"{np.float32('123')}\n"
            ">>> np.int32(12.3)\n"
        )
        # 浮点数转为整数
        f = np.float32('12345.6789')
        print(
            ">>> f = np.float32('12345.6789')\n"
            ">>> f\n"
            f"{f}\n"
            ">>> np.int32(f)\n"
            f"{np.int32(f)}\n"
            ">>> \n"
        )
        # 指定类型将序列转换为数组
        print(
            ">>> np.int32([12, 221, 555])\n"
            f"{np.int32([12, 221, 555])}\n"
        )

    @classmethod
    def str_to_num(cls):
        """调用astype方法，将字符类型转换为np.int8"""
        a = np.array(['1', 2, -12345])
        print(
            ">>> a = np.array(['1', 2])\n"
            f"{a}\n"
            ">>> a.dtype\n"
            f"{a.dtype}\n"
            ">>> a.astype(np.int8)\n"
            f"{a.astype(np.int8)}"
        )

    @classmethod
    def str_to_date(cls):
        """调用astype方法将字符串转换为日期类型np.datetime64"""
        f = np.array(["2018", "2019-01-01", "2019-02-01", "2019-01-02 08:08:08"])
        print(
            '>>> f= np.array(["2018", "2019-01-01", "2019-02-01", "2019-01-02 08:08:08"])\n' 
            ">>> f\n"
            f"{f}\n"
            ">>> f.dtype\n"
            f"{f.dtype}\n"
            ">>> f.astype(np.datetime64)\n"
            f"{f.astype(np.datetime64)}"
        )


def task(filename="stu94.csv"):
    x = np.genfromtxt(filename, dtype=np.unicode_, encoding='utf8', delimiter=',')
    print('读出数据：')
    print(x)

    y = x[:, 2].astype(np.datetime64)
    print('使用np.datatime64转换日期时间数据：')
    print(y)
    print(y.dtype)

    y2 = x[:, 2].astype('datetime64[h]')
    print('使用datetime64[h]转换日期时间数据：')
    print(y2)
    print(y2.dtype)


def training1():
    filename = "stu94.csv"
    x = np.genfromtxt(filename, dtype=np.unicode_, encoding='utf8', delimiter=',')
    print('读出数据：')
    print(x)

    y = x[:, 1].astype(np.int16)
    print('使用np.int16转换第2列数据：')
    print(y)
    print(y.dtype)


if __name__ == "__main__":
    # Preliminary.dtype_conversion()
    # Preliminary.str_to_num()
    # Preliminary.str_to_date()
    # task()
    training1()
